package cn.micai.base.lambda;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 描述：Java 8 Stream – Read a file line by line
 * <p>
 *
 * @author: 赵新国
 * @date: 2018/6/22 15:56
 */
public class ReadFileStreamExample {

    public static void main(String [] args) {

        // 1. Java 8 Read File + Stream

        String fileName = "D://newFile.txt";

        // read file into stream, try-with-resources
        /*try (Stream<String> stream1 = Files.lines(Paths.get(fileName))) {
            stream1.forEach(System.out::println);
        } catch (IOException e) {
            e.printStackTrace();
        }*/

        System.out.println("----------------------------------------------");

        // 2. Java 8 Read File + Stream + Extra

        /*List<String> list = new ArrayList<>();
        try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
            list = stream
                    .filter(line -> !line.startsWith("1This"))
                    .map(String::toUpperCase)
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }
        list.forEach(x->System.out.println(x));*/

        System.out.println("----------------------------------------------");

        // 3. BufferedReader + Stream

        /*List<String> list = new ArrayList<>();

        try (BufferedReader br = Files.newBufferedReader(Paths.get(fileName))) {

            // br returns as stream and convert it into a List
            list = br.lines().collect(Collectors.toList());

        } catch (IOException e) {
            e.printStackTrace();
        }
        list.forEach(System.out::println);*/


        System.out.println("----------------------------------------------");

        // 4. Classic BufferedReader And Scanner

        // 4.1 BufferedReader + try-with-resources example
        try (BufferedReader br = new BufferedReader(new FileReader(fileName))) {

            String line;
            while ((line = br.readLine()) != null) {
                System.out.println(line);
            }

        } catch (IOException e) {
            e.printStackTrace();
        }

        // 4.2 Scanner + try-with-resources example.
        try (Scanner scanner = new Scanner(new File(fileName))) {
            while (scanner.hasNext()) {
                System.out.println(scanner.nextLine());
            }
        } catch (IOException e) {
            e.printStackTrace();
        }




    }
}
